import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

// 账户类，存储用户账户信息
class Account {
    private String accountId; // 账户号
    private String password;  // 密码（明文存储，仅限练习）
    private double balance;   // 余额
    private List<Transaction> transactions; // 交易记录

    // 构造函数
    public Account(String accountId, String password, double balance) {
        this.accountId = accountId;
        this.password = password;
        this.balance = balance;
    }

    // Getter和Setter方法
    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public List<Transaction> getTransactions() {
        return transactions;
    }


    }


// 交易记录类，记录每笔交易详情
class Transaction {
    private String transactionId; // 交易ID
    private String type;          // 类型（存款/取款/转账）
    private double amount;        // 金额
    private LocalDateTime time;   // 交易时间
    private String targetAccount; // 转账目标账户（可选）

    // 构造函数
    public Transaction(String transactionId, String type, double amount, LocalDateTime time, String targetAccount) {
        this.transactionId = transactionId;
        this.type = type;
        this.amount = amount;
        this.time = time;
        this.targetAccount = targetAccount;
    }

    // Getter和Setter方法
    public String getTransactionId() {
        return transactionId;
    }

    public void setTransactionId(String transactionId) {
        this.transactionId = transactionId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public LocalDateTime getTime() {
        return time;
    }

    public void setTime(LocalDateTime time) {
        this.time = time;
    }

    public String getTargetAccount() {
        return targetAccount;
    }

    public void setTargetAccount(String targetAccount) {
        this.targetAccount = targetAccount;
    }
}

// 账户服务类，实现账户相关业务逻辑
class AccountService {
    public Map<String, Account> accountMap = new HashMap<>();
    private static final String ACCOUNTS_FILE = "accounts.csv";

    // 加载账户数据并修改指定账户信息
    public void loadAccounts() {
        try (BufferedReader br = new BufferedReader(new FileReader(ACCOUNTS_FILE))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 3) {
                    String accountId = parts[0];
                    String password = parts[1];
                    double balance = Double.parseDouble(parts[2]);
                    Account account = new Account(accountId, password, balance);
                    accountMap.put(accountId, account);
                }
            }
            // 找到账户并修改账户名和密码
            if (accountMap.containsKey("oldAccountId")) {
                Account accountToModify = accountMap.get("oldAccountId");
                accountToModify.setAccountId("123");
                accountToModify.setPassword("123456");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 账户登录
    public boolean login(String accountId, String password) {
        Account account = accountMap.get(accountId);
        if (account != null && account.getPassword().equals(password)) {
            return true;
        }
        return false;
    }

    // 修改密码
    public boolean changePassword(String accountId, String oldPassword, String newPassword) {
        Account account = accountMap.get(accountId);
        if (account != null && account.getPassword().equals(oldPassword)) {
            account.setPassword(newPassword);
            saveAccounts();
            return true;
        }
        return false;
    }

    // 保存账户数据到文件
    public void saveAccounts() {
        try (FileWriter fw = new FileWriter(ACCOUNTS_FILE)) {
            for (Account account : accountMap.values()) {
                fw.write(account.getAccountId() + "," + account.getPassword() + "," + account.getBalance() + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// ATM系统类，整合各模块功能，实现控制台交互
class ATMSystem {
    private AccountService accountService = new AccountService();
    private Account currentAccount;
    private Scanner scanner = new Scanner(System.in);

    public void start() {
        accountService.loadAccounts();
        accountService.saveAccounts(); // 保存修改后的账户信息到文件
        displayMainMenu();
    }

    private void displayMainMenu() {
        while (true) {
            System.out.println("=== ATM 登录界面===");
            System.out.println("1. 登录账户; 2. 查询余额; 2. 退出系统");
            System.out.print("请输入要操作的序号: ");
            try {
                int choice = scanner.nextInt();
                switch (choice) {
                    case 1:
                        login();
                        break;
                    case 2:
                        if (currentAccount != null) {
                            checkBalance();
                        } else {
                            System.out.println("请先登录账户");
                        }
                        break;
                    case 3:
                        System.out.println("退出系统");
                        return;
                    default:
                        System.out.println("无效的选择，请重新输入");
                }
            } catch (InputMismatchException e) {
                System.out.println("请输入数字");
                scanner.nextLine(); // 清空输入缓冲区
            }
        }
    }

    private void login() {
        System.out.print("请输入账户号: ");
        String accountId = scanner.next();
        System.out.print("请输入密码: ");
        String password = scanner.next();
        if (accountService.login(accountId, password)) {
            currentAccount = accountService.accountMap.get(accountId);
            System.out.println("登录成功");
            displaySubMenu();
        } else {
            System.out.println("账户号或密码错误");
            while (true) {
                System.out.println("请重新输入账户号: ");
                String newAccountId = scanner.next();
                System.out.println("请重新输入密码: ");
                String newPassword = scanner.next();
                if (accountService.login(newAccountId, newPassword)) {
                    currentAccount = accountService.accountMap.get(newAccountId);
                    System.out.println("登录成功");
                    break;
                } else {
                    System.out.println("账户号或密码错误，请再次尝试");
                }
            }
        }
    }

    private void displaySubMenu() {
        while (currentAccount != null) {
            System.out.println("===ATM 系统===");
            System.out.println("1. 存款; 2. 取款; 3. 转账; 4. 查询余额; 5. 修改密码; 6、退出;");
            System.out.print("请输入要操作的序号: ");
            try {
                int choice = scanner.nextInt();
                switch (choice) {
                    case 1:
                        deposit();
                        break;
                    case 2:
                        withdraw();
                        break;
                    case 3:
                        transfer();
                        break;
                    case 4:
                        checkBalance();
                        break;
                    case 5:
                        changePassword();
                        break;
                    case 6:
                        currentAccount = null;
                        System.out.println("已退出二级菜单");
                        break;
                    default:
                        System.out.println("无效的选择，请重新输入");
                }
            } catch (InputMismatchException e) {
                System.out.println("请输入数字");
                scanner.nextLine(); // 清空输入缓冲区
            }
        }
    }

    private void deposit() {
        System.out.print("请输入存款金额: ");
        double amount = scanner.nextDouble();
        if (amount > 0) {
            currentAccount.setBalance(currentAccount.getBalance() + amount);
            addTransaction("存款", amount, null);
            accountService.saveAccounts();
            System.out.println("存款成功，当前余额: " + currentAccount.getBalance());
        } else {
            System.out.println("存款金额必须为正数");
        }
    }

    private void withdraw() {
        System.out.print("请输入取款金额: ");
        double amount = scanner.nextDouble();
        if (amount > 0 && currentAccount.getBalance() >= amount) {
            currentAccount.setBalance(currentAccount.getBalance() - amount);
            addTransaction("取款", amount, null);
            accountService.saveAccounts();
            System.out.println("取款成功，当前余额: " + currentAccount.getBalance());
        } else {
            System.out.println("余额不足或输入金额无效");
        }
    }

    private void transfer() {
        System.out.print("请输入转账目标账户号: ");
        String targetAccountId = scanner.next();
        System.out.print("请输入转账金额: ");
        double amount = scanner.nextDouble();
        if (amount > 0 && currentAccount.getBalance() >= amount) {
            // 这里简单假设目标账户存在，实际应添加目标账户校验逻辑
            currentAccount.setBalance(currentAccount.getBalance() - amount);
            addTransaction("转账", amount, targetAccountId);
            accountService.saveAccounts();
            System.out.println("转账成功，当前余额: " + currentAccount.getBalance());
        } else {
            System.out.println("余额不足或输入金额无效");
        }
    }

    private void checkBalance() {
        System.out.println("当前余额: " + currentAccount.getBalance());
    }

    private void changePassword() {
        System.out.print("请输入旧密码: ");
        String oldPassword = scanner.next();
        System.out.print("请输入新密码: ");
        String newPassword = scanner.next();
        if (accountService.changePassword(currentAccount.getAccountId(), oldPassword, newPassword)) {
            System.out.println("密码修改成功");
        } else {
            System.out.println("旧密码错误，密码修改失败");
        }
    }

    private void addTransaction(String type, double amount, String targetAccount) {
        String transactionId = generateTransactionId();
        LocalDateTime time = LocalDateTime.now();
        Transaction transaction = new Transaction(transactionId, type, amount, time, targetAccount);
        currentAccount.getTransactions().add(transaction);
    }

    private String generateTransactionId() {
        // 简单生成交易ID，实际可采用更复杂唯一ID生成策略
        return System.currentTimeMillis() + "";
    }
}

class ATMSystemTest{
    public static void main(String[] args) {
        ATMSystem atmSystem = new ATMSystem();
        atmSystem.start();
    }
}